<?php
	define('BASE_ROOT_PATH', dirname(dirname(__FILE__)));
	include_once( BASE_ROOT_PATH . "/word/db/DBMySQL.php"); 
	function sendNotif($deviceToken,$msg)
	{
	
		$body = array("aps" => array("alert" => $msg, "badge" => 2, "sound"=>'default'));
	  	//echo $body;
	  	
		$ctx = stream_context_create();
		stream_context_set_option($ctx, "ssl", "local_cert", "apns_dev.pem");
		$fp = stream_socket_client("ssl://gateway.push.apple.com:2195", $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
		if (!$fp) {
			print "Failed to connect $err $errstr\n";
			return;
		}
		
		print "Connection OK\n";
		$payload = json_encode($body);
		$msg = chr(0) . pack("n",32) . pack("H*", str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
		print "sending message :" . $payload . "\n";
		fwrite($fp, $msg);
		fclose($fp);
		
	}

 
	// 查找用户
	$db = new DBMySQL();
	$rs = $db->Query("select msg.to_id,msg.content,msg.create_time from t_msg msg inner join msg_to_notif notif on msg.msg_id=notif.msg_id");
	//echo "select msg.to_id,msg.content,msg.create_time from t_msg msg inner join msg_to_notif notif on msg.msg_id=notif.msg_id";
	if(empty($rs)) {

		exit();
	}

	
	foreach($rs as $row)
	{
		$memberId = $row['to_id'];
		$str = "select token from t_token where member_id='$memberId'";
		echo $str;
		$devTokens=$db->Query($str);
		if(!empty($devTokens))
		{
			$deviceToken = $devTokens[0]['token'];
			echo $deviceToken;	
			sendNotif($deviceToken,$row['content']);
		}
	}
	
	

  	
?>